<!--
 * @Author: xws 1043495328@qq.com
 * @Date: 2023-07-17 17:56:27
 * @LastEditors: xws 1043495328@qq.com
 * @LastEditTime: 2023-07-28 09:31:59
 * @FilePath: \vue3-admin-template\src\views\acl\permission\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <!-- 三级组件 -->
  <Category :scene="scene" />
  <el-card style="margin: 10px 0px">
    <div v-show="scene == 0">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="categoryStore.c3Id ? false : true"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0px" :data="attrArr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column label="属性名称" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 5px"
              v-for="(item, index) in row.attrValueList"
              :key="item.id"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- row:已有的属性对象 -->
          <template #="{ row, $index }">
            <!-- 修改已有的属性按钮 -->
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateAttr(row)"
            >
              编辑
            </el-button>

            <el-popconfirm
              :title="`您确认要删除${row.attrName}吗?`"
              width="200px"
              icon="Delete"
              icon-color="red"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene == 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="attrParams.attrName ? false : true"
        @click="addAttrValue"
      >
        添加属性值
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
      <el-table
        border
        style="margin: 10px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          prop="date"
          label="序号"
          width="80px"
          type="index"
          align="center"
        />
        <el-table-column prop="date" label="属性值名称">
          <!-- row为当前属性值对象 -->
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.flag"
              @blur="toLook(row, $index)"
              placeholder="请输入属性名称"
              v-model="row.valueName"
            ></el-input>
            <div v-else @click="toEdit(row)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="属性值操作">
          <el-button
            size="small"
            type="primary"
            icon="Delete"
            @click="attrParams.attrValueList.splice(index, 1)"
          ></el-button>
        </el-table-column>
      </el-table>
      <el-button
        size="default"
        type="primary"
        @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import Category from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category'
import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/api/product/attr'
import type { AttrResponseData, AttrValue } from '@/api/product/attr/type'

import { nextTick, onBeforeMount, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryStore()
// 定义card组件内容切换
const scene = ref<number>(0) //scene=0，显示table,scene=1,展示添加与修改属性结构
const attrArr = ref<Attr[]>([])
const addAttr = () => {
  Object.assign(attrParams, {
    attrName: '', //新增的属性的名字
    attrValueList: [
      //新增的属性值数组
    ],
    categoryId: categoryStore.c3Id, //三级分类的ID
    categoryLevel: 3, //代表的是三级分类
  })
  scene.value = 1
}
//table表格修改已有属性按钮的回调
const updateAttr = (row: Attr) => {
  scene.value = 1
  //将已有的属性对象赋值给attrParams对象即为
  //ES6->Object.assign进行对象的合并
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

//搜集新增的属性数据
const attrParams = reactive<Attr>({
  attrName: '', //新增的属性的名字
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: '', //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
})
//监听仓库三级分类ID变化
watch(
  () => categoryStore.c3Id,
  () => {
    // 清空上一次的数据
    attrArr.value = []
    // 保证三级分类得有才能发请求
    if (!categoryStore.c3Id) return

    //获取分类的ID
    getAttr()
  },
)
//添加属性值按钮的回调
const addAttrValue = () => {
  //点击添加属性值按钮的时候,向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //控制每一个属性值编辑模式与切换模式的切换
  })
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([])
const cancel = () => {
  scene.value = 0
}
//属性值表单元素失却焦点事件回调
const toLook = (row: AttrValue, $index: number) => {
  if (row.valueName.trim() == '') {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  const reprat = attrParams.attrValueList.find((item) => {
    //切记把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (reprat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
  }
  //相应的属性值对象flag:变为false,展示div
  row.flag = false
}
//属性值div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  //相应的属性值对象flag:变为true,展示input
  row.flag = true
  //nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  //获取分类下的己有的属性与属性值
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  // console.log('result: ', result);
  if (result.code == 200) {
    attrArr.value = result.data
  }
}
const save = async () => {
  const result: any = await reqAddOrUpdateAttr(attrParams)
  console.log('result: ', result)
  if (result.code == 200) {
    //切换场景
    scene.value = 0
    //提示信息
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    //获取全部已有的属性与属性值
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
const deleteAttr = async (attrId: number) => {
  //点击确定按钮删除已有请求
  const result:any = await reqRemoveAttr(attrId)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    //再次发请求获取已有的数据
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeMount(() => {
  // 清空仓车的数据
  categoryStore.$reset();
})
</script>

<style scoped></style>
